package com.wzf.utils;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;

public class TableUtils {


    public static String getTableName(JSONObject object){
        if(null==object){
            return "";
        }
        JSONObject source = object.getJSONObject("source");
        if(null!=source && null!=source.getString("table")){
            return source.getString("table");
        }
        return "";
    }

    public static boolean tableNameEq(JSONObject object,String tableName){
       return getTableName(object).equals(tableName);
    }

    public static String getColVal(JSONObject object,String col){
        JSONObject after =  object.getJSONObject("after");
        String val=null;
        if(null!=after){
            val = after.getString(col);
        }else {
            JSONObject before =  object.getJSONObject("before");
            if(null!=before){
                val = before.getString(col);
            }
        }
        return val;
    }

    /**
     * 检查某个字段是否发生了变化
     * */
    public static boolean isChangeCol(JSONObject object,String col){
        JSONObject after =  object.getJSONObject("after");
        JSONObject before =  object.getJSONObject("before");
        if(null==after||null==before){
            return true;
        }
        String beforeVal = before.getString(col);
        String afterVal = after.getString(col);
        if(!StrUtil.equals(beforeVal,afterVal)){
            return true;
        }
        return false;
    }


    /**
     * 取值，更新前
     * */
    public static String getBeforeVal(JSONObject object,String col){
        JSONObject before =  object.getJSONObject("before");
        if(null==before){
            return null;
        }
        String beforeVal = before.getString(col);
        return beforeVal;
    }

    /**
     * 取值，更新后
     * */
    public static String getAfterVal(JSONObject object,String col){
        JSONObject after =  object.getJSONObject("after");
        if(null==after){
            return null;
        }
        String afterVal = after.getString(col);
        return afterVal;
    }
}
